using UnityEngine;
using TMPro;
using UnityEngine.UI;
using UI.BankingPanel.Data;
using System;
using System.Collections.Generic;

namespace UI.BankingPanel.Components
{
    /// <summary>
    /// 头部统计信息组件 - 纯UI组件，只负责显示和用户输入收集
    /// </summary>
    public class C_Header_Statistics : MonoBehaviour
    {
        #region UI组件引用 - 按节点结构组织
        [Header("平均吃码输入")]
        private TMP_InputField averageEatCodeInput;
        private TextMeshProUGUI averageEatCodeLabel;
        
        [Header("最多亏损输入")]
        private TMP_InputField maxLossLimitInput;
        private TextMeshProUGUI maxLossLimitLabel;
        
        [Header("显示文本组件")]
        private TextMeshProUGUI totalBetText;
        private TextMeshProUGUI totalEatText;
        private TextMeshProUGUI totalReportText;
        private TextMeshProUGUI oddsText;
        
        [Header("盈亏统计显示")]
        private TextMeshProUGUI winText;        // 盈余个数显示
        private TextMeshProUGUI loseText;       // 亏损个数显示
        #endregion
        
        #region 回调事件 - 遵循MVC，UI只通知不处理
        /// <summary>
        /// 平均吃码输入变化回调
        /// </summary>
        public event Action<float> OnAverageEatCodeChanged;
        
        /// <summary>
        /// 最大亏损限制输入变化回调
        /// </summary>
        public event Action<float> OnMaxLossLimitChanged;
        #endregion
        
        #region 初始化
        /// <summary>
        /// 初始化组件
        /// </summary>
        public void Initialize()
        {
            Debug.Log($"[C_Header_Statistics] 开始初始化组件");
            FindUIComponents();
            SetupInputListeners();
            Debug.Log("[C_Header_Statistics] 组件初始化完成");
        }
        
        /// <summary>
        /// 查找UI组件 - 按照节点结构
        /// </summary>
        private void FindUIComponents()
        {
            Debug.Log("[C_Header_Statistics] 开始查找UI组件...");
            
            // 平均吃码输入组件
            var averageEatCodeNode = transform.Find("AverageEatCode_Input");
            if (averageEatCodeNode != null)
            {
                averageEatCodeLabel = FindTextInBackground(averageEatCodeNode, "Background");
                averageEatCodeInput = FindInputInValue(averageEatCodeNode, "Background_Value");
                Debug.Log($"[C_Header_Statistics] 平均吃码组件: 标签={averageEatCodeLabel != null}, 输入框={averageEatCodeInput != null}");
            }
            
            // 最大亏损输入组件
            var maxLossLimitNode = transform.Find("MaxLossLimit_Input");
            if (maxLossLimitNode != null)
            {
                maxLossLimitLabel = FindTextInBackground(maxLossLimitNode, "Background");
                maxLossLimitInput = FindInputInValue(maxLossLimitNode, "Background_Value");
                Debug.Log($"[C_Header_Statistics] 最大亏损组件: 标签={maxLossLimitLabel != null}, 输入框={maxLossLimitInput != null}");
            }
            
            // 显示文本组件
            totalBetText = FindDisplayText("Total_Bet_Text");
            totalEatText = FindDisplayText("Total_Eat_Text");
            totalReportText = FindDisplayText("Total_Report_Text");
            oddsText = FindDisplayText("Odds_Text");
            
            // 盈亏统计显示组件
            winText = FindDisplayText("win_Text");
            loseText = FindDisplayText("lose_Text");
            
            Debug.Log($"[C_Header_Statistics] 显示组件查找完成: 总投注={totalBetText != null}, 总吃码={totalEatText != null}, 总报表={totalReportText != null}, 赔率={oddsText != null}");
            Debug.Log($"[C_Header_Statistics] 盈亏统计组件查找完成: 盈余个数={winText != null}, 亏损个数={loseText != null}");
        }
        
        /// <summary>
        /// 在背景节点中查找文本组件
        /// </summary>
        private TextMeshProUGUI FindTextInBackground(Transform parent, string backgroundName)
        {
            var background = parent.Find(backgroundName);
            if (background != null)
            {
                var textTransform = background.Find("Text");
                if (textTransform != null)
                {
                    return textTransform.GetComponent<TextMeshProUGUI>();
                }
            }
            return null;
        }
        
        /// <summary>
        /// 在数值背景节点中查找输入框组件
        /// </summary>
        private TMP_InputField FindInputInValue(Transform parent, string valueName)
        {
            var valueBackground = parent.Find(valueName);
            if (valueBackground != null)
            {
                var inputTransform = valueBackground.Find("Value_Input");
                if (inputTransform != null)
                {
                    return inputTransform.GetComponent<TMP_InputField>();
                }
            }
            return null;
        }
        
        /// <summary>
        /// 查找显示文本组件
        /// </summary>
        private TextMeshProUGUI FindDisplayText(string nodeName)
        {
            var node = transform.Find(nodeName);
            if (node != null)
            {
                var valueBackground = node.Find("Background_Value");
                if (valueBackground != null)
                {
                    var textTransform = valueBackground.Find("Text");
                    if (textTransform != null)
                    {
                        return textTransform.GetComponent<TextMeshProUGUI>();
                    }
                }
            }
            return null;
        }
        
        /// <summary>
        /// 设置输入框监听器
        /// </summary>
        private void SetupInputListeners()
        {
            // 平均吃码输入监听
            if (averageEatCodeInput != null)
            {
                averageEatCodeInput.onEndEdit.AddListener(OnAverageEatCodeInputChanged);
                Debug.Log("[C_Header_Statistics] 平均吃码输入监听器已设置");
            }
            
            // 最大亏损输入监听
            if (maxLossLimitInput != null)
            {
                maxLossLimitInput.onEndEdit.AddListener(OnMaxLossLimitInputChanged);
                Debug.Log("[C_Header_Statistics] 最大亏损输入监听器已设置");
            }
        }
        #endregion
        
        #region 输入事件处理 - 只收集数据，不处理业务逻辑
        /// <summary>
        /// 平均吃码输入变化处理
        /// </summary>
        private void OnAverageEatCodeInputChanged(string value)
        {
            if (float.TryParse(value, out float result))
            {
                Debug.Log($"[C_Header_Statistics] 平均吃码输入: {result}");
                OnAverageEatCodeChanged?.Invoke(result);
            }
            else
            {
                Debug.LogWarning($"[C_Header_Statistics] 平均吃码输入格式错误: {value}");
                // 重置为0
                if (averageEatCodeInput != null)
                {
                    averageEatCodeInput.text = "0";
                }
            }
        }
        
        /// <summary>
        /// 最大亏损输入变化处理
        /// </summary>
        private void OnMaxLossLimitInputChanged(string value)
        {
            if (float.TryParse(value, out float result))
            {
                Debug.Log($"[C_Header_Statistics] 最大亏损输入: {result}");
                OnMaxLossLimitChanged?.Invoke(result);
            }
            else
            {
                Debug.LogWarning($"[C_Header_Statistics] 最大亏损输入格式错误: {value}");
                // 重置为0
                if (maxLossLimitInput != null)
                {
                    maxLossLimitInput.text = "0";
                }
            }
        }
        #endregion
        
        #region 显示更新方法 - 只负责UI显示
        /// <summary>
        /// 设置平均吃码显示值（由Controller调用）
        /// </summary>
        public void SetAverageEatCodeDisplay(float value)
        {
            if (averageEatCodeInput != null)
            {
                averageEatCodeInput.text = value == 0 ? "0" : value.ToString("0.##");
            }
        }
        
        /// <summary>
        /// 设置最大亏损显示值（由Controller调用）
        /// </summary>
        public void SetMaxLossLimitDisplay(float value)
        {
            if (maxLossLimitInput != null)
            {
                maxLossLimitInput.text = value == 0 ? "0" : value.ToString("0.##");
            }
        }
        
        /// <summary>
        /// 设置总投注显示
        /// </summary>
        public void SetTotalBetDisplay(float value)
        {
            if (totalBetText != null)
            {
                totalBetText.text = value == 0 ? "0" : value.ToString("0.##");
            }
        }
        
        /// <summary>
        /// 设置总吃码显示
        /// </summary>
        public void SetTotalEatDisplay(float value)
        {
            if (totalEatText != null)
            {
                totalEatText.text = value == 0 ? "0" : value.ToString("0.##");
            }
        }
        
        /// <summary>
        /// 设置总报表显示
        /// </summary>
        public void SetTotalReportDisplay(float value)
        {
            if (totalReportText != null)
            {
                totalReportText.text = value == 0 ? "0" : value.ToString("0.##");
            }
        }
        
        /// <summary>
        /// 设置赔率显示
        /// </summary>
        public void SetOddsDisplay(float value)
        {
            if (oddsText != null)
            {
                oddsText.text = value == 0 ? "0" : value.ToString("0.#");
            }
        }
        
        /// <summary>
        /// 设置盈余个数显示
        /// </summary>
        public void SetWinCountDisplay(int count)
        {
            if (winText != null)
            {
                winText.text = count.ToString();
            }
        }
        
        /// <summary>
        /// 设置亏损个数显示
        /// </summary>
        public void SetLoseCountDisplay(int count)
        {
            if (loseText != null)
            {
                loseText.text = count.ToString();
            }
        }
        
        /// <summary>
        /// 根据风险值数据统计盈亏个数并更新显示
        /// </summary>
        /// <param name="numberBetDataList">号码风险数据列表</param>
        public void UpdateRiskStatistics(List<NumberBetData> numberBetDataList)
        {
            if (numberBetDataList == null || numberBetDataList.Count == 0)
            {
                SetWinCountDisplay(0);
                SetLoseCountDisplay(0);
                return;
            }
            
            int winCount = 0;   // 盈余个数（风险值 > 0）
            int loseCount = 0;  // 亏损个数（风险值 < 0）
            
            foreach (var numberData in numberBetDataList)
            {
                if (numberData.riskValue > 0)
                {
                    winCount++;
                }
                else if (numberData.riskValue < 0)
                {
                    loseCount++;
                }
                // 风险值 = 0 的不计入统计
            }
            
            SetWinCountDisplay(winCount);
            SetLoseCountDisplay(loseCount);
            
            Debug.Log($"[C_Header_Statistics] 风险统计已更新 - 盈余个数:{winCount}, 亏损个数:{loseCount}");
        }
        
        /// <summary>
        /// 批量更新统计显示数据
        /// </summary>
        public void UpdateStatisticsDisplay(StatisticsData data)
        {
            if (data == null) return;
            
            SetTotalBetDisplay(data.revenueTotal);
            SetTotalEatDisplay(data.eatCodeTotal);
            SetTotalReportDisplay(data.reportTotal);
            SetOddsDisplay(data.odds);
            
            Debug.Log($"[C_Header_Statistics] 统计显示已更新 - 总投注:{data.revenueTotal}, 总吃码:{data.eatCodeTotal}, 总报表:{data.reportTotal}, 赔率:{data.odds}");
        }
        
        /// <summary>
        /// 批量更新统计显示数据（包含风险统计）
        /// </summary>
        /// <param name="data">统计数据</param>
        /// <param name="numberBetDataList">号码风险数据列表</param>
        public void UpdateStatisticsDisplay(StatisticsData data, List<NumberBetData> numberBetDataList)
        {
            UpdateStatisticsDisplay(data);
            UpdateRiskStatistics(numberBetDataList);
        }
        #endregion
        
        #region 清理
        private void OnDestroy()
        {
            // 清理事件监听
            if (averageEatCodeInput != null)
            {
                averageEatCodeInput.onEndEdit.RemoveListener(OnAverageEatCodeInputChanged);
            }
            
            if (maxLossLimitInput != null)
            {
                maxLossLimitInput.onEndEdit.RemoveListener(OnMaxLossLimitInputChanged);
            }
        }
        #endregion
    }
} 